// pages/preview/preview.js
const app = getApp()
const storage = require('../../utils/cache.js')
const api = require('../../utils/api.js')
const util = require('../../utils/util.js')
const login = require('../../utils/login.js')
const config = require('../../config/config');
import Scratch from "../../components/scratch/scratch.js"
var backgroundAudioManager
Page({
  data: {
    scrollindex: 0,  //当前页面的索引值
    isAllScreen: config.isAllScreen,
    play: true,
    isPay: false,
    shareNums: 5,
    share: true
  },
  onLoad: function (query) {
    let that = this
    const scene = decodeURIComponent(query.scene)
    if (scene != 'undefined' && scene != null && scene != '') {
      this.setData({
        giftId: scene
      })
    } else {
      this.setData({
        giftId: query.giftId
      })
    }
    storage.get('openid').then(res => {
      if (res.errMsg === "getStorage:ok") {
        this.setData({
          openid: res.data
        })
      } else {
        this.setData({
          openid: ''
        })
      }
      this.getGift(this.data.openid, this.data.giftId)
    })
    wx.getSavedFileList({
      success(res) {
        console.log(res.fileList)
        that.playAudio(res.fileList[0].filePath)
      }
    })
  },
  onShow(){
    util.checkOpenid().then((res) => {
      if (res == 'true') {
        this.setData({
          haveOpenid: true,
        })
      } else {
        this.setData({
          haveOpenid: false,
        })
      }
    })
  },
  getUserInfo(){
    login.login(this.data.giftId).then(res => {
      console.log(res)
      if (res.error == 0) {
        this.setData({
          haveOpenid: true,
          hide: true
        }),
          this.getGift(res.data.openid, this.data.giftId)
      } else {
        util.showFail(res.msg)
      }
    })
  },
  getGift(openid, id) {
    let data = {
      openid,
      id
    }
    api.POST('user/getGift', data).then(res => {
      if (res.error == 0) {
        this.setData({
          data: res.data,
          content: res.data.three.price,
          imgUrls: res.data.one.url,
          isPay: res.data.is_pay,
          price: res.data.price,
          logo: res.data.logo,
          nickname: res.data.nickname,
          share: res.data.share
        })
        this.scratch = new Scratch(this, {
          canvasWidth: 408,
          canvasHeight: 502,
          imageResource: res.data.four.cover,
          r: 10,
          awardTxt: res.data.four.content,
          awardTxtColor: '#fed452',
          awardTxtFontSize: '16px',
          callstart:()=>{
            this.setData({
              showShadow:true
            })
          }
        })
      } else {
        util.showFail(res.msg)
      }
    })
  },
  // 文字转换成数组
  getData(story) {
    let that = this
    var story = story
    var i = 0;
    var time = setInterval(function () {
      var text = story.substring(0, i);
      i++;
      that.setData({
        text: text
      });
      if (text.length == story.length) {
        clearInterval(time);
      }
    }, 500)
  },
  hideShadow(){
    this.setData({
      hide: true
    })
  },
  getOne(){
    this.setData({
      scrollindex: 0,
      muted: true
    })
  },
  getTwo(){
    this.setData({
      scrollindex: 1,
      previewcss: false,
      muted: false,
      zoomIn: false
    })
    this.getData(this.data.data.two.content)
    this.setData({
      video: this.data.data.two.path
    })
  },
  getThree(){
    this.setData({
      scrollindex: 2,
      previewcss: true,
      muted: true,
      zoomIn: true
    })
  },
  getfour(){
    this.setData({
      scrollindex: 3,
      previewcss: false,
      zoomIn: false
    })
    this.move(this.data.isPay)
  },
  onShareAppMessage(res){
    console.log(this.data.shareNums)
    let index = this.data.shareNums
    index--
    console.log(index)
    if(res) {
      setTimeout(() => {
        this.setData({
          shareNums: index
        })
        console.log(this.data.shareNums)
        if (this.data.shareNums == 0) {
          this.setData({
            isPay: true,
            showShadow: false
          })
          this.scratch.start()
        }
      },1000)
    }
    return {
      title: `${this.data.data.nickname}送给你的2019新年大礼包~`,
      imageUrl: '../../img/share.png',
      path: `/pages/preview/preview?giftId=${this.data.giftId}`
    }
  },
  refuse(){
    this.setData({
      showShadow: false
    })
  },
  accept(){
    this.pay()
  },
  move(isStart){
    if (isStart) {
      this.scratch.start()
    } else {
     return
    }
  },
  pay() {
    let _this = this
      let data = {
        openid: wx.getStorageSync('openid'),
        proid: this.data.giftId,
        type: 1,
        money: 1
      }
      api.POST('weChatPay/createOrder', data).then(res => {
        if (res.error == 0) {
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: 'MD5',
            paySign: res.data.paySign,
            success(res) {
              _this.setData({
                isPay: true,
                showShadow: false
              })
              _this.scratch.start()
              // _this.move(_this.data.isPay)
            },
            fail(res) {
              console.log('用户取消支付')
            }
          })
        } else {
          util.showFail(res.msg)
        }
      })
  },
  // 我也要制作
  toHome() {
    wx.redirectTo({
      url: '../home/home',
    })
  },
  // 背景音乐
  onMusicTap: function () {
    let that = this
    wx.getSavedFileList({
      success(res) {
        console.log(res.fileList)
        that.playAudio(res.fileList[0].filePath)
      }
    })
  },
  // 播放音乐
  playAudio(url) {
    backgroundAudioManager = wx.getBackgroundAudioManager()
    // 设置了 src 之后会自动播放
    backgroundAudioManager.title = "天天音乐";
    backgroundAudioManager.src = url;
    backgroundAudioManager.play();
    backgroundAudioManager.onPlay(() => {
      console.log('音乐播放')
    })
    backgroundAudioManager.onEnded(() => {
      // console.log("音乐播放结束");
      backgroundAudioManager.play()
    })
    backgroundAudioManager.onPause(() =>{
      console.log('音乐暂停了')
    })
  },
  //播放活着暂停
  playOrPause() {
    let that = this
    console.log(that.data.play)
    that.setData({
      play: !this.data.play
    })
    console.log(that.data.play)
    if (that.data.play == false) {
      backgroundAudioManager.pause()
    } else {
      backgroundAudioManager.play()
    }
  },
  onHide() {
    // this.setData({
    //   shareNums: 5
    // })
  },
  onUnload() {
    backgroundAudioManager.stop()
  },
  getRank(){
    console.log(this.data)
    let data = {
      openid: wx.getStorageSync('openid')
    }
    console.log(data)
    api.POST('user/getRankList', data).then(res => {
      if (res.error == 0) {
        console.log(res)
        this.setData({
          list: res.data.list,
          self: res.data.self,
          showRank: true
        })
      }
    })
  },
  closeRank(){
    this.setData({
      showRank: false
    })
  },
  close() {
    this.setData({
      showShadow: false
    })
  }
})